<script>
    export default {
        name: 'Table',
        componentName: 'Table',
        props: {
            columns: {
                type: Array,
                required: true,
                default:() => []
            },
            remote: {
                type: Function,
            },
            pageSizes: {
                type: Array,
                default: () => [10, 20, 50, 100],
            },
            layout: {
                type: String,
                default: 'total, sizes, prev, pager, next, jumper',
            },
            showPagination: {
                type: Boolean,
                default: true,
            },
        },
        data() {
            return {
                loading: false,
                data: [],
                height: 0,
                pagination: {
                    pageSize: 10,
                    current: 1,
                    total: 0,
                    showSizeChanger: true,
                    showQuickJumper: true,
                },
            };
        },
        created() {
            this.$on('Table:height', this.setHeight);
        },
        methods: {
            setHeight(value) {
                this.height = value;
            },
            handleChange(pagination) {
                this.pagination = pagination;
                this.fetch();
            },
            clear() {
                this.pagination = Object.assign(this.pagination, {
                    total: 0,
                    current: 0,
                });
                this.data = [];
            },
            async fetch() {
                if (this.loading) return;
                this.loading = true;
                const { data = [], size = 0, total = 0, current = 0 } = await this.remote({
                    pageSize: this.pagination.pageSize || 10,
                    pageNum: this.pagination.current || 1,
                }).catch((err) => {
                    console.error(err);
                    return {};
                });
                this.pagination = Object.assign(this.pagination, {
                    pageSize: size || 10,
                    total,
                    current,
                });
                this.data = data;
                this.loading = false;
            },
            refetch(current = 1) {
                // 从第一页开始加载
                this.pagination = Object.assign(this.pagination, {
                    current,
                });
                this.fetch();
            },
            handleSizeChange(value) {
                // 从第一页开始加载
                this.pagination = Object.assign(this.pagination, {
                    current: 1,
                    pageSize: value || 10,
                });
                this.fetch();
            },
            getColumn(item) {
                const scopedSlots = {};
                const children = [];

                if (item.scopedSlots) {
                    Object.assign(scopedSlots, item.scopedSlots);
                }

                if (item.render) {
                    Object.assign(scopedSlots, {
                        default: item.render,
                    });
                }
                return {
                    props: { ...item },
                    scopedSlots,
                    children,
                };
            },
            selectionChange(selection) {
                this.$emit('selected', selection);
            },
            renderSingleColumn(item, index) {
                const { props, scopedSlots } = this.getColumn(item);
                const attrs = {
                    props: {
                        key: `${props.label}+${index}`,
                        ...props,
                        align: "center",
                        formatter(row, column, cellValue) {
                            return cellValue === null || cellValue === '' || cellValue === undefined ? '--' : cellValue;
                        },
                    },
                    scopedSlots,
                };

                if (Array.isArray(item.children) && item.children.length) {
                    return <el-table-column {...attrs}>{this.renderColumn(item.children)}</el-table-column>;
                }

                return <el-table-column {...attrs}></el-table-column>;
            },
            renderColumn(columns) {
                return (Array.isArray(columns) ? columns : []).map(this.renderSingleColumn);
            },
        },
        render() {
            const directives = [
                {
                    name: 'loading',
                    value: this.loading,
                },
            ];

            const attrs = {
                stripe: true,
                border: true,
                data: this.data,
                ...this.$attrs,
            };

            // 设置最大高度，用于和上层组件配合
            if (this.height) {
                attrs.height = this.height;
            }
            const on = {
                'selection-change': this.selectionChange,
                ...this.$listeners,
            };

            const scopedSlots = {
                empty: () => <span class='text-danger'>没有查询到相关信息</span>,
                ...this.$scopedSlots,
            };

            return (
                <div class='component-table' {...{ directives }}>
                    <el-table props={attrs} on={on} scopedSlots={scopedSlots}>
                        {this.renderColumn(this.columns)}
                    </el-table>
                    {this.showPagination ? (
                        <el-pagination
                            on-size-change={this.handleSizeChange}
                            on-current-change={this.refetch}
                            current-page={this.pagination.current}
                            page-sizes={this.pageSizes}
                            page-size={this.pagination.pageSize}
                            layout={this.layout}
                            total={this.pagination.total}
                        ></el-pagination>
                    ) : (
                        ''
                    )}
                </div>
            );
        },
    };
</script>

<style lang="scss">
    /* common-table2 */
    $secondary-color: #909399;

    // .common-table2__content .el-table th
    .component-table {
        padding: 0 15px;
        // // flex: 1;
        // display: flex !important;
        // flex-direction: column !important;
        .el-table {
            height: 100%;
            // &__empty-block {
            //     display: none;

            //     + .el-table__append-wrapper {
            //         display: flex;
            //         height: 100%;
            //         flex-direction: column;
            //         justify-content: center;
            //     }
            // }
        }

        .el-table th {
            background: #f7f7f7;
        }

        .el-table td {
            height: 60px;
        }
        [class^='el-icon-'],
        [class*=' el-icon-'] {
            font-size: 16px;
            vertical-align: text-bottom
        }

        .el-pagination {
            text-align: right;
            margin-top: 5px;
        }
        .el-pagination__total {
            float: left;
        }

        .no-results-content {
            /*padding-top: 110px;*/
            // color: $secondary-color;
            line-height: 1.2;

            .text-danger {
                font-size: 16px;
            }
        }
    }
</style>
